package cn.bqjr.eily.samples.service.commom.impl;

import cn.bqjr.eily.core.utils.SysConfigUtils;
import cn.bqjr.eily.redis.spring.boot.IRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class RedisServiceImpl implements IRedisService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void put(String key, Object value, long expire) {
        redisTemplate.opsForValue().set(getKey(key), value, expire, TimeUnit.MILLISECONDS);
    }

    @Override
    public void put(String key, Object value) {
        redisTemplate.opsForValue().set(getKey(key), value);
    }

    @Override
    public <T> T get(String key, Class<T> cls) {
        return (T) redisTemplate.opsForValue().get(getKey(key));
    }

    @Override
    public void delete(String key) {
        redisTemplate.delete(getKey(key));
    }

    @Override
    public void delete(Collection<String> keys) {
        keys.stream().forEach(key -> redisTemplate.delete(getKey(key)));
    }

    @Override
    public void expire(String key, long expire) {
        redisTemplate.expire(getKey(key), expire, TimeUnit.MILLISECONDS);
    }

    @Override
    public Long getExpire(String key) {
        return redisTemplate.getExpire(getKey(key));
    }

    @Override
    public Long getExpire(String key, TimeUnit unit) {
        return redisTemplate.getExpire(getKey(key), unit);
    }

    @Override
    public boolean exist(String key) {
        return redisTemplate.hasKey(getKey(key));
    }

    @Override
    public Set<String> keys(String pattern) {
        return redisTemplate.keys(getKey(pattern));
    }

    private String getKey(String key) {
        return SysConfigUtils.getCacheKey(key);
    }
}
